package top.cyuw.subjectsystem.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListIntegerToVarcharTypeHandler implements TypeHandler<List<Integer>> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<Integer> list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, list.stream().map(String::valueOf).collect(Collectors.joining(",")));
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, String s) throws SQLException {
        return toList(resultSet.getString(s));
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, int i) throws SQLException {
        return toList(resultSet.getString(i));
    }

    @Override
    public List<Integer> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return toList(callableStatement.getString(i));
    }

    private List<Integer> toList(String result) {
        if (StringUtils.isNotEmpty(result)) {
            String[] split = result.split(",");
            List<Integer> list = new ArrayList<>(split.length);
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }
            return list;
        }
        return Collections.emptyList();
    }

}
